import 'package:flutter/material.dart';
import 'product.dart';

/**
 * 购物车
 */
class ShoppingList extends StatefulWidget {

  //商品列表
  final List<Product> products;

  const ShoppingList({Key key, this.products}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new _ShoppingListState();
  }
}

class _ShoppingListState extends State<ShoppingList> {

  @override
  void initState() {
    super.initState();
    //初始化只需要执行一次的代码
  }


  @override
  void dispose() {
    super.dispose();
    //进行资源回收
  }
  //选中的商品
  Set<Product> _shoppingCart = new Set<Product>();

  void _handleCartChanged(Product product, bool inCart) {
    setState(() {
      if (inCart)
        _shoppingCart.add(product);
      else
        _shoppingCart.remove(product);
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Shopping List"),
      ),
      body: new ListView(
        padding: new EdgeInsets.symmetric(vertical: 8.0),
        children: widget.products.map((Product product) {
          return new ShoppingListItem(product: product,inCart: _shoppingCart.contains(product),cartChangedCallback: _handleCartChanged);
        }).toList()
      ),
    );
  }
}